package com.jlect.swebing.ui.client;

import com.jlect.swebing.renderers.client.DefaultRenderers;
import com.jlect.swebing.renderers.client.Renderer;
import com.jlect.swebing.renderers.client.RenderersConfig;
import com.jlect.swebing.renderers.client.RootPanelRenderer;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Root panel component. 
 * @author Sergey Kozmin
 * @since 11.11.2007 20:18:45
 */
public class GRootPanel extends GComponent {
    private static boolean isInitialized = false;
    private static Map contentPanels = new HashMap();

    public GRootPanel() {
        setFocusPolicy(new ChildCyclicFocusTraversalPolicy(this));
    }

    public GContainer getContentPanel() {
        return getContentPanel(null);
    }

    public GContainer getContentPanel(String id) {
        return contentPanels.containsKey(id) ? (GContainer)contentPanels.get(id) : createNewPanel(id);
    }

    private GContainer createNewPanel(String id) {
        GContainer container = new GContainer();
        getRootPanelRenderer().getRootPanel(id).addElement(container.getRenderer());
        contentPanels.put(id, container);
        addComponent(container);

        if(!isInitialized) {
            FocusManagerProvider.getFocusManager().requestFocus(container);
        }
        return container;
    }

    public void clearComponents() {
        contentPanels.clear();
    }

    public void removeComponent(String id) {
        GComponent comp = (GComponent) contentPanels.remove(id);
        super.removeComponent(comp);
    }

    public void removeComponent(GComponent component) {
        if(component == null) {
            throw new IllegalArgumentException("Could not remove null component. ");
        }
        Set keySet = contentPanels.keySet();
        for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
            String id = (String) iterator.next();
            if(component.equals(contentPanels.get(id))) {
                removeComponent(id);
                break;
            }
        }
    }

    public GComponent removeComponent(int index) {
        throw new IllegalStateException("Could not remove component by index "
                + "from Root Panel. Use #removeComponent(String id) instead. ");
    }

    private RootPanelRenderer getRootPanelRenderer() {
        return (RootPanelRenderer) getRenderer();
    }

    protected Renderer createRenderer() {
        return RenderersConfig.getRenderersFactory().createComponentRenderer(DefaultRenderers.ROOT_PANEL.getName());
    }

    public void setParent(GComponent parent) {
        throw new IllegalStateException("Could not attach Root Panel component to a component. ");
    }
}
